<template>
  <el-col v-if="widget.type === 'grid-col'"
    class="grid-cell"
    v-bind="layoutProps"
    :class="[selected ? 'selected' : '', customClass]"
    :style="colHeightStyle"
    :key="widget.id"
    @click.stop="selectWidget(widget)">
    <draggable :list="widget.widgetList"
      item-key="id"
      :group="{name: 'dragGroup', pull: (isInLayoutSync && isSyncFromLeft) ? 'clone' : true, put: !isSyncFromLeft}"
      :clone="(isInLayoutSync && isSyncFromLeft) ? handleClone : undefined"
      ghost-class="ghost"
      :animation="200"
      tag="transition-group"
      :component-data="{name: 'fade'}"
      handle=".drag-handler"
      @add="(evt) => onGridDragAdd(evt, widget.widgetList)"
      @update="onGridDragUpdate"
      :move="checkContainerMove">
      <template #item="{ element: subWidget, index: swIdx }">
        <div class="form-widget-list">
          <template v-if="'container' === subWidget.category">
            <component :is="subWidget.type + '-widget'"
              :widget="subWidget"
              :designer="designer"
              :key="subWidget.id"
              :parent-list="widget.widgetList"
              :index-of-parent-list="swIdx"
              :parent-widget="widget"></component>
          </template>
          <template v-else>
            <component :is="subWidget.type + '-widget'"
              :field="subWidget"
              :designer="designer"
              :key="subWidget.id"
              :parent-list="widget.widgetList"
              :index-of-parent-list="swIdx"
              :parent-widget="widget"
              :design-state="true"></component>
          </template>
        </div>
      </template>
    </draggable>

    <div class="widget-action grid-col-action"
      v-if="designer.selectedId === widget.id && widget.type === 'grid-col'">
      <i :title="i18nt('designer.hint.selectParentWidget')"
        @click.stop="selectParentWidget(widget)">
        <VfIcon name="iv-icon-back" />
      </i>
      <i v-if="!!parentList && (parentList.length > 1)"
        :title="i18nt('designer.hint.moveUpWidget')"
        @click.stop="moveUpWidget()">
        <VfIcon name="iv-icon-move-up" />
      </i>
      <i v-if="!!parentList && (parentList.length > 1)"
        :title="i18nt('designer.hint.moveDownWidget')"
        @click.stop="moveDownWidget()">
        <VfIcon name="iv-icon-move-down" />
      </i>
      <i :title="i18nt('designer.hint.cloneWidget')"
        @click.stop="cloneGridCol(widget)">
        <VfIcon name="iv-icon-clone" />
      </i>
      <i :title="i18nt('designer.hint.remove')"
        @click.stop="removeWidget">
        <VfIcon name="iv-icon-delete" />
      </i>
    </div>

    <div class="widget-label grid-col-handler"
      v-if="designer.selectedId === widget.id && widget.type === 'grid-col'">
      <i>{{i18nt('designer.widgetLabel.' + widget.type)}}</i>
    </div>
  </el-col>
</template>

<script>
import i18n from "@/utils/i18n"
import FieldComponents from '@/components/form-designer/form-widget/field-widget/index'
import refMixinDesign from "@/components/form-designer/refMixinDesign"
import { useNamespace } from 'element-plus'; // 导入useNamespace

export default {
  name: "GridColWidget",
  componentName: "GridColWidget",
  mixins: [i18n, refMixinDesign],
  inject: ['refList'],
  components: {
    ...FieldComponents,
  },
  props: {
    widget: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,
    gridParentWidget: Object, // 添加gridParentWidget属性用于点击复制

    colHeight: {
      type: String,
      default: null
    },

  },

  data() {
    return {
      ns: useNamespace('grid-col', 'rk'), // 使用导入的useNamespace
      layoutProps: {
        span: this.widget.options.span,
        // md: this.widget.options.md || 12,
        // sm: this.widget.options.sm || 12,
        // xs: this.widget.options.xs || 12,
        offset: this.widget.options.offset || 0,
        push: this.widget.options.push || 0,
        pull: this.widget.options.pull || 0,
      },
      // 添加左侧列表备份数据
      leftListsBackup: []
    }
  },
  computed: {
    selected() {
      return this.widget.id === this.designer.selectedId
    },

    customClass() {
      return this.widget.options.customClass || ''
    },

    colHeightStyle() {
      return !!this.colHeight ? { height: this.colHeight + 'px' } : {}
    },

    // 判断是否在同步布局组件内
    isInLayoutSync() {
      // 首先尝试通过parentWidget链检查
      let parent = this.parentWidget;
      let depth = 0;
      while (parent && depth < 10) { // 限制深度以防止无限循环
        if (parent.type === 'layout-sync') {
          return true;
        }
        // 特殊处理：如果父组件是grid，继续检查grid的父组件
        if (parent.type === 'grid') {
          if (parent.parentWidget) {
            parent = parent.parentWidget;
            depth++;
            continue;
          } else {
            break;
          }
        }

        // 特殊处理：如果父组件是tab，继续检查tab的父组件
        if (parent.type === 'tab') {
          if (parent.parentWidget) {
            parent = parent.parentWidget;
            depth++;
            continue;
          } else {
            break;
          }
        }
        parent = parent.parentWidget;
        depth++;
      }
      return false;
    },
    // 判断元素是否来自同步布局的左侧
    isSyncFromLeft() {
      // 检查元素是否有位置标识
      if (this.widget && this.widget.hasOwnProperty('_layoutPosition')) {
        const isFromLeft = this.widget._layoutPosition === 'left';
        return isFromLeft;
      }
      return false;
    }
  },
  watch: {
    'designer.formConfig.layoutType': {
      handler(val) {
        if (!!this.widget.options.responsive) {
          if (val === 'H5') {
            this.layoutProps.span = this.widget.options.xs || 12
          } else if (val === 'Pad') {
            this.layoutProps.span = this.widget.options.sm || 12
          } else {
            this.layoutProps.span = this.widget.options.md || 12
          }
        } else {
          this.layoutProps.span = this.widget.options.span || 12
        }
      }
    },

    'widget.options.responsive': {
      handler(val) {
        let lyType = this.designer.formConfig.layoutType
        if (!!val) {
          if (lyType === 'H5') {
            this.layoutProps.span = this.widget.options.xs || 12
          } else if (lyType === 'Pad') {
            this.layoutProps.span = this.widget.options.sm || 12
          } else {
            this.layoutProps.span = this.widget.options.md || 12
          }
        } else {
          this.layoutProps.span = this.widget.options.span || 12
        }
      }
    },

    'widget.options.span': {
      handler(val) {
        this.layoutProps.span = val
      }
    },

    'widget.options.md': {
      handler(val) {
        this.layoutProps.span = val
      }
    },

    'widget.options.sm': {
      handler(val) {
        this.layoutProps.span = val
      }
    },

    'widget.options.xs': {
      handler(val) {
        this.layoutProps.span = val
      }
    },

    'widget.options.offset': {
      handler(val) {
        this.layoutProps.offset = val
      }
    },

    'widget.options.push': {
      handler(val) {
        this.layoutProps.push = val
      }
    },

    'widget.options.pull': {
      handler(val) {
        this.layoutProps.pull = val
      }
    },

  },
  created() {
    this.initRefList()
    this.initLayoutProps()
  },
  methods: {
    initLayoutProps() {
      if (!!this.widget.options.responsive) {
        let lyType = this.designer.formConfig.layoutType
        if (lyType === 'H5') {
          this.layoutProps.span = this.widget.options.xs || 12
        } else if (lyType === 'Pad') {
          this.layoutProps.span = this.widget.options.sm || 12
        } else {
          this.layoutProps.span = this.widget.options.md || 12
        }
      } else {
        this.layoutProps.span = this.widget.options.span
      }
    },

    // 重构判断函数，确保能正确识别来自左侧列表的元素（包括嵌套在grid-col中的元素）
    isElementFromLeftList(element) {
      // 首先检查元素本身是否带有 _isFromLeft 标识
      if (element && element.hasOwnProperty('_isFromLeft') && element._isFromLeft === true) {
        return true;
      }

      // 检查是否是容器组件且包含来自左侧的嵌套元素
      if (element && element.category === 'container') {
        let hasLeftElement = false;

        // 处理 grid 容器
        if (element.type === 'grid' && element.cols && Array.isArray(element.cols)) {
          for (let col of element.cols) {
            if (col && col.widgetList && Array.isArray(col.widgetList)) {
              for (let widget of col.widgetList) {
                if (this.isElementFromLeftList(widget)) {
                  hasLeftElement = true;
                  break;
                }
              }
            }
            if (hasLeftElement) break;
          }
        }

        // 处理 tab 容器
        if (element.type === 'tab' && element.tabs && Array.isArray(element.tabs)) {
          for (let tab of element.tabs) {
            if (tab && tab.widgetList && Array.isArray(tab.widgetList)) {
              for (let widget of tab.widgetList) {
                if (this.isElementFromLeftList(widget)) {
                  hasLeftElement = true;
                  break;
                }
              }
            }
            if (hasLeftElement) break;
          }
        }

        // 特别处理 grid-col 容器
        if (element.type === 'grid-col' && element.widgetList && Array.isArray(element.widgetList)) {
          for (let widget of element.widgetList) {
            if (this.isElementFromLeftList(widget)) {
              hasLeftElement = true;
              break;
            }
          }
        }

        // 处理其他容器的 widgetList
        if (element.widgetList && Array.isArray(element.widgetList) &&
          element.type !== 'grid' && element.type !== 'tab' && element.type !== 'grid-col') {
          for (let widget of element.widgetList) {
            if (this.isElementFromLeftList(widget)) {
              hasLeftElement = true;
              break;
            }
          }
        }

        // 处理自定义容器组件，如左右布局等
        if (element.leftLists && Array.isArray(element.leftLists) && !hasLeftElement) {
          for (let widget of element.leftLists) {
            if (this.isElementFromLeftList(widget)) {
              hasLeftElement = true;
              break;
            }
          }
        }
        if (element.rightLists && Array.isArray(element.rightLists) && !hasLeftElement) {
          for (let widget of element.rightLists) {
            if (this.isElementFromLeftList(widget)) {
              hasLeftElement = true;
              break;
            }
          }
        }
        return hasLeftElement;
      }

      return false;
    },

    // 重构深度克隆函数，确保所有嵌套元素都被正确克隆并分配唯一ID
    deepCloneComponent(original) {
      if (!original) return original;

      // 深度克隆组件
      const cloned = JSON.parse(JSON.stringify(original));

      // 生成新的唯一ID
      const generateNewId = () => {
        return 'widget' + Math.random().toString(36).substring(2, 10) + Date.now().toString(36);
      };

      // 递归处理所有嵌套组件的ID
      const processWidgetIds = (widget) => {
        if (!widget) return;

        // 为当前组件生成新ID
        const oldId = widget.id;
        widget.id = generateNewId();

        if (widget.guid) {
          const oldGuid = widget.guid;
          widget.guid = generateNewId().toUpperCase();
        }

        // 递归处理容器组件的子组件
        if (widget.category === 'container') {
          // 处理 grid 容器
          if (widget.type === 'grid' && widget.cols && Array.isArray(widget.cols)) {
            widget.cols.forEach((col) => {
              if (col) {
                col.id = generateNewId();
                if (col.guid) {
                  col.guid = generateNewId().toUpperCase();
                }
                // 递归处理 grid-col 内部的 widgetList
                if (col.widgetList && Array.isArray(col.widgetList)) {
                  col.widgetList.forEach(processWidgetIds);
                }
              }
            });
          }

          // 处理 tab 容器
          if (widget.type === 'tab' && widget.tabs && Array.isArray(widget.tabs)) {
            widget.tabs.forEach((tab) => {
              if (tab) {
                tab.id = generateNewId();

                if (tab.guid) {
                  tab.guid = generateNewId().toUpperCase();
                }

                // 递归处理 tab 内部的 widgetList
                if (tab.widgetList && Array.isArray(tab.widgetList)) {
                  tab.widgetList.forEach(processWidgetIds);
                }
              }
            });
          }

          // 特别处理 grid-col 容器
          if (widget.type === 'grid-col' && widget.widgetList && Array.isArray(widget.widgetList)) {
            widget.widgetList.forEach(processWidgetIds);
          }

          // 处理其他容器的 widgetList
          if (widget.widgetList && Array.isArray(widget.widgetList) &&
            widget.type !== 'grid' && widget.type !== 'tab' && widget.type !== 'grid-col') {
            widget.widgetList.forEach(processWidgetIds);
          }

          // 处理自定义容器组件，如左右布局等
          if (widget.leftLists && Array.isArray(widget.leftLists)) {
            widget.leftLists.forEach(processWidgetIds);
          }
          if (widget.rightLists && Array.isArray(widget.rightLists)) {
            widget.rightLists.forEach(processWidgetIds);
          }
        }
      };

      processWidgetIds(cloned);
      return cloned;
    },

    handleClone(original) {
      // 检查是否在同步布局内
      if (!this.isInLayoutSync) {
        // 返回原对象
        return original;
      }
      const cloned = this.deepCloneComponent(original);
      return cloned;
    },
    // 创建左侧列表备份
    createLeftListsBackup() {
      // 清空现有备份
      this.leftListsBackup.splice(0, this.leftListsBackup.length);

      // 查找layout-sync-widget祖先组件并获取其左侧列表
      let parent = this.$parent;
      while (parent) {
        if (parent.$options && parent.$options.name === 'LayoutSyncWidget') {
          // 获取layout-sync-widget的左侧列表
          const leftLists = parent.widget.leftLists;
          if (leftLists && Array.isArray(leftLists)) {
            leftLists.forEach(item => {
              this.leftListsBackup.push(JSON.parse(JSON.stringify(item)));
            });
          }
          break;
        }
        parent = parent.$parent;
      }
    },

    // 添加恢复左侧列表的方法
    restoreLeftLists() {
      // 查找layout-sync-widget祖先组件并恢复其左侧列表
      let parent = this.$parent;
      while (parent) {
        if (parent.$options && parent.$options.name === 'LayoutSyncWidget') {
          // 获取layout-sync-widget的左侧列表
          const leftLists = parent.widget.leftLists;
          if (leftLists && Array.isArray(leftLists)) {
            // 恢复左侧列表
            leftLists.splice(0, leftLists.length);

            this.leftListsBackup.forEach(item => {
              leftLists.push(JSON.parse(JSON.stringify(item)));
            });

            // 重新标记元素
            parent.markLeftListElements();
          }
          break;
        }
        parent = parent.$parent;
      }
    },

    onGridDragAdd(evt, subList) {
      const newIndex = evt.newIndex;
      if ((newIndex === undefined) || (newIndex === null)) {
        return;
      }

      // 检查是否是添加到grid-col内部还是添加到其他地方
      // 如果是在同步布局中，需要检查目标位置
      if (this.isInLayoutSync) {

        // 查找拖拽目标是否是layout-sync-widget的右侧列表
        let targetIsRightList = false;
        let parent = this.$parent;
        let depth = 0;

        // 遍历父组件查找是否有添加到右侧列表的情况
        while (parent && depth < 15) {
          // 检查是否是draggable组件并且是添加操作
          if (parent.$options && parent.$options._componentTag === 'draggable') {
            // 检查这个draggable是否属于layout-sync-widget的右侧列表
            const parentVue = parent.$parent;
            if (parentVue && parentVue.$options && parentVue.$options.name === 'LayoutSyncWidget') {
              // 检查是否是右侧列表的draggable
              targetIsRightList = true;
              break;
            }
          }
          parent = parent.$parent;
          depth++;
        }

        if (targetIsRightList) {
          return;
        }
      }

      if (!!subList[newIndex]) {
        // 检查是否在同步布局中
        const isInSyncLayout = this.isInLayoutSync;
        const newWidget = subList[newIndex];
        if (!!newWidget) {
          let clonedWidget = null;

          // 只有在同步布局中才进行克隆操作
          if (isInSyncLayout) {
            // 检查是否是从左侧列表拖拽过来的
            const isFromLeft = this.isElementFromLeftList && this.isElementFromLeftList(newWidget);

            // 仅当组件来自左侧时才进行克隆（从左到右拖拽）
            if (isFromLeft) {
              // 使用同步布局自己的深度克隆方法
              clonedWidget = this.deepCloneComponent(newWidget);

              // 如果成功克隆，则替换原组件
              if (clonedWidget) {
                // 移除克隆组件的 _isFromLeft 标识，因为它现在已经是右侧的组件了
                if (clonedWidget.hasOwnProperty('_isFromLeft')) {
                  delete clonedWidget._isFromLeft;
                }
                // 标记为右侧组件
                clonedWidget._dragSource = 'right';

                subList.splice(newIndex, 1, clonedWidget);
                this.designer.setSelected(clonedWidget);
              } else {
                // 即使克隆失败，也要移除 _isFromLeft 标识
                if (newWidget.hasOwnProperty('_isFromLeft')) {
                  delete newWidget._isFromLeft;
                }
                // 标记为右侧组件
                newWidget._dragSource = 'right';
                this.designer.setSelected(newWidget);
              }
            } else {
              // 右侧内部拖拽
              // 移除 _isFromLeft 标识
              if (newWidget.hasOwnProperty('_isFromLeft')) {
                delete newWidget._isFromLeft;
              }
              // 标记为右侧组件
              newWidget._dragSource = 'right';
              this.designer.setSelected(newWidget);
            }
          } else {
            // 移除 _isFromLeft 标识
            if (newWidget.hasOwnProperty('_isFromLeft')) {
              delete newWidget._isFromLeft;
            }
            this.designer.setSelected(newWidget);
          }
        }

        this.designer.emitHistoryChange();
      }
    },

    onGridDragUpdate() {
      this.designer.emitHistoryChange()
    },

    selectWidget(widget) {
      this.designer.setSelected(widget)
    },

    checkContainerMove(evt) {
      return this.designer.checkWidgetMove(evt)
    },

    /**
     * 通过parentList获取父组件
     */
    getParentWidgetFromList(parentList) {
      // 查找refList中与parentList匹配的组件
      if (this.refList) {
        for (let key in this.refList) {
          let component = this.refList[key];
          if (component && component.widget && component.widget.cols === parentList) {
            return component.widget;
          }
        }
      }
      return null;
    },

    selectParentWidget() {
      if (this.parentWidget) {
        this.designer.setSelected(this.parentWidget)
      } else {
        this.designer.clearSelected()
      }
    },

    moveUpWidget() {
      this.designer.moveUpWidget(this.parentList, this.indexOfParentList)
    },

    moveDownWidget() {
      this.designer.moveDownWidget(this.parentList, this.indexOfParentList)
    },

    /**
     * 获取父级grid组件
     */
    getParentGridWidget() {
      // 如果parentList是grid的cols，则parentWidget应该是grid组件
      if (this.parentList && this.parentWidget && this.parentWidget.cols === this.parentList) {
        return this.parentWidget;
      }

      // 尝试通过parent链查找
      let parent = this.parentWidget;
      while (parent) {
        if (parent.cols && Array.isArray(parent.cols)) {
          return parent;
        }
        parent = parent.parentWidget;
      }

      return null;
    },

    cloneGridCol(widget) {
      let targetParentWidget = this.parentWidget || this.gridParentWidget;

      // 同步布局中，确定正确父组件
      if (this.isInLayoutSync) {

        // 首先尝试使用gridParentWidget（如果是grid）
        if (this.gridParentWidget && this.gridParentWidget.type === 'grid') {
          targetParentWidget = this.gridParentWidget;
        }
        // 如果parentWidget是layout-sync，需要进一步判断
        else if (this.parentWidget && this.parentWidget.type === 'layout-sync') {
          // 查找当前widget在哪个列表中
          if (this.parentWidget.leftLists &&
            this.parentWidget.leftLists.some(item => item.id === widget.id)) {
            // widget在左侧列表中
            targetParentWidget = this.parentWidget;
          } else if (this.parentWidget.rightLists &&
            this.parentWidget.rightLists.some(item => item.id === widget.id)) {
            // widget在右侧列表中
            targetParentWidget = this.parentWidget;
          } else {
            // widget在grid中，使用gridParentWidget
            targetParentWidget = this.gridParentWidget || this.parentWidget;
          }
        }
      }

      // 如果parentWidget为空，尝试通过parentList查找
      if (!targetParentWidget && this.parentList) {
        // 查找包含当前widget的父组件
        for (let i = this.indexOfParentList - 1; i >= 0; i--) {
          const item = this.parentList[i];
          if (item && item.cols && Array.isArray(item.cols)) {
            // 检查item.cols中是否有当前widget
            const found = item.cols.find(col => col === widget || (col && col.id === widget.id));
            if (found) {
              targetParentWidget = item;
              break;
            }
          }
        }

        // 如果还没找到，尝试往后查找
        if (!targetParentWidget) {
          for (let i = this.indexOfParentList + 1; i < this.parentList.length; i++) {
            const item = this.parentList[i];
            if (item && item.cols && Array.isArray(item.cols)) {
              // 检查item.cols中是否有当前widget
              const found = item.cols.find(col => col === widget || (col && col.id === widget.id));
              if (found) {
                targetParentWidget = item;
                break;
              }
            }
          }
        }
      }

      // 如果仍然为空，尝试通过widget的parent链查找
      if (!targetParentWidget) {
        // 遍历parentWidget链查找具有cols属性的组件
        let currentParent = this.parentWidget;
        let depth = 0;
        while (currentParent && depth < 10) {
          if (currentParent.cols && Array.isArray(currentParent.cols)) {
            // 检查currentParent.cols中是否有当前widget
            const found = currentParent.cols.find(col => col === widget || (col && col.id === widget.id));
            if (found) {
              targetParentWidget = currentParent;
              break;
            }
          }
          currentParent = currentParent.parentWidget;
          depth++;
        }
      }

      // 特殊处理：如果仍然找不到，尝试在当前组件的上下文中查找
      if (!targetParentWidget) {
        // 检查当前组件是否在grid的cols中
        if (this.parentList && Array.isArray(this.parentList)) {
          // parentList就是grid的cols
          const gridWidget = this.getParentGridWidget();
          if (gridWidget) {
            targetParentWidget = gridWidget;
          }
        }
      }
      if (!targetParentWidget) {
        return;
      }
      this.designer.cloneGridCol(widget, targetParentWidget)
    },

    removeWidget() {
      if (!!this.parentList) {
        let nextSelected = null
        if (this.parentList.length === 1) {
          if (!!this.parentWidget) {
            nextSelected = this.parentWidget
          }
        } else if (this.parentList.length === (1 + this.indexOfParentList)) {
          nextSelected = this.parentList[this.indexOfParentList - 1]
        } else {
          nextSelected = this.parentList[this.indexOfParentList + 1]
        }

        this.parentList.splice(this.indexOfParentList, 1)
        //this.designer.setSelected(nextSelected)
      }
    },


  }
}
</script>

<style lang="scss" scoped>
@import "@/components/form-designer/form-widget/styles/widget-action.scss";

.grid-cell {
  min-height: 38px !important;
  //margin: 6px 0;  /* 设置了margin，栅格列的offset、push、pull会失效！！ */
  padding: 3px;
  outline: 1px dashed #d9d9d9;
  position: relative;
  .form-widget-list {
    min-height: 28px;
  }
}
</style>